import configparser
import os

from redis import Redis

import peekRoom
import makeInfoFile
import streamRec
from multiprocessing import Process
import argparse

from utils.message import VideoMessage
from utils.bloader import UpLoaderPlus
from utils.erro import PeekError
from upload import get_info, getTagAndDynamic


def run_proc(uper: UpLoaderPlus, video_files, video_title, channel, tag_str, video_desc, video_url, graph_path,
             dynamic_str):
    uper.upVideo(video_files, video_title, channel, tag_str, video_desc, video_url, graph_path, dynamic_str)


if __name__ == '__main__':

    """
        命令行参数
    """
    parser = argparse.ArgumentParser(description='上传bilibili视频')
    parser.add_argument('-y', '--youtube_channel', help='youtube channel id',
                        required=True)
    parser.add_argument('-c', '--channel', type=int,
                        help='频道id, 详见https://github.com/FortuneDayssss/BilibiliUploader/wiki',
                        required=True)
    parser.add_argument('-p', '--proxy', action="store_false", help='open proxy?')
    parser.add_argument('-r', '--redismode', action="store_true", help='use redis模式?')
    parser.add_argument('-l', '--maxlength', type=int, default=2500, help='bilibili简介长度限制，每个分区不同，参考投稿页进行设置')
    args = parser.parse_args()

    url = f'https://www.youtube.com/channel/{args.youtube_channel}/live'
    # url = 'https://www.youtube.com/channel/UC0Owc36U9lOyi9Gx9Ic-4qg/live'

    """
        读取配置
    """
    cf = configparser.ConfigParser()
    cf.read("./db.conf")


    """
        启用redis模式会关闭上传功能
    """
    uper = None
    if not args.redismode:

        if not (cf.has_option("cookie", "passwd") and cf.has_option("cookie", "user")):
            raise FileExistsError("请在db.conf中修改添加正确的cookie配置")

        uper = UpLoaderPlus(username=cf.get("cookie", "user"), passwd=cf.get("cookie", "passwd"))

    """
        Loop循环监听
    """
    while 1 == 1:

        return_status = peekRoom.room(url, args.proxy)

        if return_status:
            """
                监控和下载
            """
            task_id = makeInfoFile.info_file(url, args.proxy)
            streamRec.graph(task_id, args.proxy)
            video_files = streamRec.stream(task_id, args.proxy)

            video_title, graph_path, video_desc, video_url = get_info(task_id, args.maxlength)
            tag_str, dynamic_str = getTagAndDynamic()

            print(video_files, video_title, args.channel, tag_str.rstrip(), video_url, graph_path, dynamic_str,
                  sep="\n",
                  end="\n")
            print(video_desc)

            """
                上传或发送redis消息
            """
            if not args.redismode:
                p = Process(target=run_proc, args=(
                    uper, video_files, video_title, args.channel, tag_str, video_desc, video_url, graph_path,
                    dynamic_str,))
                p.start()
                """
                    生产消息
                """
                password = cf.get("redis", "password")
                host = cf.get("redis", "host")
                queue = cf.get("redis", "queue")
                print(password,host,queue)
                messageObj = VideoMessage(video_files, args.channel, video_title, graph_path, video_desc, video_url,
                                          tag_str,
                                          dynamic_str)
                print(messageObj.toJson())

                with Redis(host=host, password=password) as redis_conn:
                    for i in range(10):
                        redis_conn.lpush(queue, messageObj.toJson())
                print("push end")
        else:
            raise PeekError()
